package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.managerplus.key.service.KeyGeneratorServicePrx;
import com.mp.approvalreq.entity.*;
import com.mp.approvalreq.entity.adjust.VersionInfo;
import com.mp.approvalreq.service.SubmitRequestServicePrx;
import com.mp.approvalreq.util.*;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import com.plusmoney.redis.RedisUtils;
import com.plusmoney.util.Utils;
import com.qq.tars.client.util.ServantUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * 提交审批
 *
 * @author Administrator
 */
@WebServlet("/submit")
public class SubmitRequest extends AbstractServlet {

    private static final Logger logger = LoggerFactory.getLogger(SubmitRequest.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try {

            User user = getReqUser(req);
            String reqBody = getContent(req);
            logger.info("json参数 {}", reqBody);

            Request request = JSONObject.parseObject(reqBody, Request.class);
            initRequest(request, user);

            check(request);

            SubmitRequestServicePrx submitRequestService = ServiceUtils.getSubmitRequestServicePrx();
            KeyGeneratorServicePrx keyGeneratorService = ServantUtils.getObject(KeyGeneratorServicePrx.class);

            initRequestDkey(request, keyGeneratorService);
            initApprovalNum(request);

            VersionInfo versionInfo = getVersionInfo(req);
            request.setVersionInfo(versionInfo);

            request = submitRequestService.submitRequest(request);

            returnJson(resp, request);
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    private void initRequest(Request request, User user) {

        initComponentsContent(request, user);

        initRelatePeopleList(request);
    }


    private void returnJson(HttpServletResponse resp, Request request) throws IOException {
        JSONObject jsonStr = new JSONObject();
        jsonStr.put("result", "0");
        jsonStr.put("res_info", "提交成功");
        jsonStr.put("requestDkey", request.getRequestDkey());
        jsonStr.put("requestAncestorId", request.getRequestAncestorId());

        logger.info("return:{}", jsonStr);

        printJson(resp, jsonStr.toJSONString());
    }


    private void initRequestDkey(Request request, KeyGeneratorServicePrx keyGeneratorService) throws Throwable {
        List<TemplateComponent> list = request.getComponentsContent();
        List<Integer> dbkList = keyGeneratorService.generateKeys("requestApproval", list.size() + 1);

        for (int i = 0; i < dbkList.size(); i++) {
            if (i == 0) {
                request.setRequestDkey(dbkList.get(i));
                request.setRequestAncestorId(dbkList.get(i));
            } else {
                request.getComponentsContent().get(i - 1).setDbkey(dbkList.get(i));
            }
        }
    }

    private void initRelatePeopleList(Request request) {
        if (StringUtils.isNotEmpty(request.getRelaPeopleListStr())) {
            try {
                request.setRelaPeopleList(JSONArray.parseArray(request.getRelaPeopleListStr(), People.class));
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
                throw new RpcServerLogicalException(1, "审批内容不能为空");
            }
        }
    }

    private void initComponentsContent(Request request, User user) {
        //设置用户信息
        request.setUser(user);
        String componentsContentsStr = request.getComponentsContentsStr();
        try {
            List<TemplateComponent> componentsContent = JSONArray.parseArray(componentsContentsStr, TemplateComponent.class);
            request.setComponentsContent(componentsContent);
            request.setComponentsContentsStr(null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RpcServerLogicalException(1, "审批内容不能为空");
        }
    }

    protected void check(Request request) {
        if (request.getTemplateId() == 0 || request.getVersion() == 0) {
            throw new RpcServerLogicalException(1, "审批内容不能为空");
        }

        if (request.getComponentsContent() == null || request.getComponentsContent().size() == 0) {
            throw new RpcServerLogicalException(1, "审批内容不能为空");
        }

        if (Utils.isNotEmpty(request.getCcList())) {
            if (request.getCcList().size() > 30) {
                throw new RpcServerLogicalException(1, "最多添加30个抄送人");
            }
        }

        try {
            Jedis jedis = RedisUtils.getJedis();
            if (jedis.exists(request.getContactIdSubmitTime())) {
                RedisUtils.close(jedis);
                throw new RpcServerLogicalException("002", "提交成功");
            }
            RedisUtils.close(jedis);
        } catch (RpcServerLogicalException e) {
            throw e;
        } catch (Throwable throwable) {
            logger.error("redis异常", throwable);
        }
    }


    private void initApprovalNum(Request request) {
        try {
            String num = NumberBuilder.getApprovalNum();
            logger.info("该审批编号: " + num);
            request.setApprovalNum(num);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            throw new RpcServerLogicalException(1, "当前人员过多,请稍后提交");
        }
    }


}
